package com.sample.library.portlet.book;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.PortletRequestUtils;
import org.springframework.web.portlet.mvc.AbstractController;

import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.sample.library.service.BookLocalServiceUtil;

public class ViewController extends AbstractController implements InitializingBean {

	public void afterPropertiesSet() throws Exception {
	}
	
	public ModelAndView handleRenderRequest(RenderRequest renderRequest, RenderResponse renderResponse)
			throws Exception {
		ModelAndView view = new ModelAndView();
		String action = PortletRequestUtils.getStringParameter(renderRequest, "action");
		if (action != null && "viewBook".equals(action) || action != null && "viewHome".equals(action))
		{
			view.setViewName("book/view");
		}
		return view;
	}
	
	public void handleActionRequest(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
		String action = PortletRequestUtils.getStringParameter(actionRequest, "action", "");
		long[] deleteSelectedIds = StringUtil.split(ParamUtil.getString(actionRequest, "deleteRowIds"), 0L);
		if( deleteSelectedIds != null && deleteSelectedIds.length > 0) {
			for (int i = 0; i < deleteSelectedIds.length; i++) {
				BookLocalServiceUtil.deleteBook(deleteSelectedIds[i]);
			}
			actionResponse.setRenderParameter("action", "viewBook");
		} 
		else	{
			super.handleActionRequest(actionRequest, actionResponse);
		}
	}
	
}
